package com.Drools.CIPS.ruler;

import com.Drools.CIPS.bean.Rulers;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.*;
import org.kie.api.definition.KiePackage;
import org.kie.api.definition.rule.Rule;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;

import java.util.*;

public class MTRuler {
    private static KieServices kieServices;//这个是全局常量，唯一
    private static KieContainer kieContainer;//持有所有规则、函数等的引用

    private static KieFileSystem kieFileSystem;//包含了所有规则文件
    private static KieBuilder kieBuilder ;//用于构建这些规则文件
    private static String path = "src/main/resources/rules/";

    static {
        kieServices = KieServices.Factory.get();//这个是全局常量，唯一
        kieFileSystem = kieServices.newKieFileSystem();
    }

    public static void addRulerString(String ruler,String file){
        kieFileSystem.write(path + file + ".drl",
                ruler.getBytes());//加入规则
        kieBuilder = kieServices.newKieBuilder(kieFileSystem);
        kieBuilder.buildAll();//将 kieBuilder 里的规则 构建
        kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());
    }

    /**
     * 单笔 添加
     * @param rulers
     */
    public static void addRuler(Rulers rulers){
        System.out.println(rulers);
        kieFileSystem.write(path + rulers.getFileName() + ".drl",
                rulers.ruler().getBytes());//加入规则
        kieBuilder = kieServices.newKieBuilder(kieFileSystem);
        kieBuilder.buildAll();//将 kieBuilder 里的规则 构建

        //将 新的规则 在kieContainer里重新构建 必须重新构建
        kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());
    }

    /**
     * 批量添加 规则
     * @param list
     */
    public static void addAllRuler(List<Rulers> list){
        for (Rulers rulers:list){
            kieFileSystem.write(path + rulers.getFileName() + ".drl",
                    rulers.ruler().getBytes());//加入规则
        }
//        kieFileSystem.writeKModuleXML()//添加 mxl的配置
        kieBuilder = kieServices.newKieBuilder(kieFileSystem);
        kieBuilder.buildAll();//将 kieBuilder 里的规则 构建

        //将 新的规则 在kieContainer里重新构建
        kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());
    }

    /**
     * 单笔删除
     * @param file
     * @return
     */
    public static String deleteRuler(String file){
        try {
            kieFileSystem.delete(path + file + ".drl");//删除规则
            kieBuilder = kieServices.newKieBuilder(kieFileSystem);
            kieBuilder.buildAll();//将 kieBuilder 里的规则 构建

            //将 新的规则 在kieContainer里重新构建
            kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());
        }catch (Exception e){
            return "没找到此规则文件删除" + file + "失败";
        }
        return "删除" + file + "成功";
    }

    /**
     * KieBase 级别的删除，不会删除kieFileSystem
     * @param packageName
     * @param ruleName
     * @return
     */
    public static String deleteRuler(String packageName,String ruleName){
        try {

            KieBase kieBase = kieContainer.getKieBase();
            if(ruleName!=null&&!ruleName.trim().equals("")){
                kieBase.removeRule(packageName,ruleName);//删除指定包，指定规则名的规则
            }else {
                kieBase.removeKiePackage(packageName);//删除指定包的所有规则
            }
        }catch (Exception e){
            return "没找到此规则文件删除失败";
        }
        return "删除成功";
    }

    /**
     * 获取规则
     * @return
     */
    public static Map<String,List<String>> getRulers(){///包名  ：【规则名】
        KieBase kieBase = kieContainer.getKieBase();
        Collection<KiePackage> kiePackages = kieBase.getKiePackages();//获取有多少  package 的包名


        Map<String,List<String>> ruler = new HashMap<>();
        for (KiePackage s:kiePackages){//便利 每个包
            List<String> list = new ArrayList<>();
            ruler.put(s.getName(),list);
            for (Rule r:s.getRules()){//便利每个包下的 规则
                list.add(r.getName());
            }
        }
        return ruler;
    }

    /**
     * 执行规则
     * @param m
     * @param s
     * @return
     */
    public static int use(Map<String, Object> m, String s){

        KieBase kieBase = kieContainer.getKieBase();
        KieSession kieSession = kieBase.newKieSession();
        kieSession.insert(m);
        int i = kieSession.fireAllRules();//使用规则
        kieSession.dispose();//关闭规则
        return i;
    }

    /**
     * 执行指定分组的规则
     * @param m
     * @param all
     * @return
     */
    public static int useGroup(Map<String, Object> m, String all){

        KieBase kieBase = kieContainer.getKieBase();
        KieSession kieSession = kieBase.newKieSession();
        if(all!=null&&!all.trim().equals("")){
            String[] ss = all.split(";");
            for (String s:ss){
                kieSession.getAgenda().getAgendaGroup(s).setFocus();
            }
        }
        kieSession.insert(m);
        int i = kieSession.fireAllRules();//使用规则
        kieSession.dispose();//关闭规则
        return i;
    }


    public static Object test(){

        return null;
    }
}
